package com.dz.lm.web.controller.comp;

import com.alibaba.fastjson.JSONObject;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.FileUploadUtil;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.common.utils.StringUtils;
import com.dz.lm.common.utils.json.JsonUtils;
import com.dz.lm.domain.compremark.CompRemark;
import com.dz.lm.service.comp.comp.CompService;
import com.dz.lm.service.comp.remark.CompRemarkService;
import com.dz.lm.service.comp.user.CompUserService;
import com.dz.lm.web.controller.Basic2Control;
import com.smartlbs.util.UploadFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/rewriteUrl/comp/user")
public class CompUserController extends Basic2Control {
    public Logger logger = LogManager.getLogger(CompUserController.class);
    @Autowired
    private CompService compService;
    @Autowired
    private CompUserService compUserService;
    @Autowired
    private CompRemarkService compRemarkService;
    /**
     * 注册
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/register")
    public Map add(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //手机号
        String phone = param.get("phone") != null ? param.get("phone").toString() : "";
        //密码
        String password = param.get("password") != null ? param.get("password").toString() : "";
        //公司
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        //部门角色
        Integer roleId = param.get("roleId") != null ?StringUtil.getInt(param.get("roleId").toString(),0) :0;


        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(phone) || compId == 0 ) {
            message = "参数有误";
        } else {
            int register = compUserService.register(phone, password, compId, roleId);
            if (register > 0) {
                result = "00";
                message = "注册成功";
            } else if (register == -997) {
                result = "01";
                message = "用户不存在";
            } else if (register == -998) {
                message = "密码不正确";
            }else if(register == -996){
                message = "已注册。";
            }
        }
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }

    /**
     * 登录
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/login")
    public Map login(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //手机号
        String userName = param.get("userName") != null ? param.get("userName").toString() : "";
        //公司码
        String code = param.get("code") != null ? param.get("code").toString() : "";
        //密码
        String password = param.get("password") != null ? param.get("password").toString() : "";

        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(userName)  ) {
            message = "参数有误";
        } else {

                Map login = compUserService.login(userName, password, 0);
                if (!login.isEmpty()) {
                    data = login;
                    int type = StringUtil.getInt(login.get("type"), 0);
                    if(type > 0){
                        result = "00";
                        message = "登录成功";
                    }else if( type == -999){
                        result = "01";
                        message = "用户未注册";
                    }else if(type == -998){
                        result = "01";
                        message = "用户未绑定公司";
                    }else if(type == -997){
                        result = "01";
                        message = "密码错误";
                    }else if(type == -996){
                        result = "01";
                        message = "公司未审核，暂时无法登录";
                    }else if(type == -995){
                        result = "01";
                        message = "审核未通过，请联系相关公司负责人";
                    }
                } else {
                    message = "登录失败";
                }

        }
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 用户审核
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/userReivew")
    public Map userReivew(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //用id
        Integer pid = param.get("pid") != null ? Integer.parseInt(param.get("pid").toString()) : 0;
        // 1审核通过  2审核未通过
        Integer status = param.get("status") != null ? Integer.parseInt(param.get("status").toString()) : 0;
        //部门id
        Integer roleId = param.get("roleId") != null ? Integer.parseInt(param.get("roleId").toString()) : 0;


        int i = compUserService.reivew(pid,status,roleId);
        if(i > 0){
            result = "00";
            message = "审核成功";
        }
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 用户删除
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/deleteUser")
    public Map deleteUser(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //用户id
        Integer pid = param.get("pid") != null ? Integer.parseInt(param.get("pid").toString()) : 0;

        int i = compUserService.delete(pid);
        if(i > 0){
            result = "00";
            message = "删除成功";
        }
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 用户查询
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/queryUser")
    public Map queryUser(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //公司
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        //部门角色
        Integer roleId = param.get("roleId") != null ? Integer.parseInt(param.get("roleId").toString()) : 0;
        Integer pageNum = param.get("pageNum") != null ? Integer.parseInt(param.get("pageNum").toString()) : 1;
        Integer rows = param.get("rows") != null ? Integer.parseInt(param.get("rows").toString()) : 10;
        //0 未审核 1审核通过  2审核未通过
        Integer type = param.get("type") != null ? StringUtil.getInt(param.get("type").toString(),-1) : -1;
        data = compUserService.query(pageNum, rows,compId,roleId,type);
        result = "00";
        message = "获取成功";
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }

    /**
     * 用户管理
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/queryApply")
    public Map queryApply(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //登录名 姓名
        String name = param.get("name") != null ? param.get("name").toString() : "";
        //省
        String province = param.get("province") != null ? param.get("province").toString() : "";
        //公司
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        //部门角色
        Integer roleId = param.get("roleId") != null ? StringUtil.getInt(param.get("roleId").toString(),0) : 0;
        Integer pageNum = param.get("pageNum") != null ? Integer.parseInt(param.get("pageNum").toString()) : 1;
        Integer rows = param.get("rows") != null ? Integer.parseInt(param.get("rows").toString()) : 10;
        //用户
        Integer userId = param.get("userId") != null ? StringUtil.getInt(param.get("userId").toString(),0) : 0;
        //状态 1 待接单 2拒绝
        //3-已提交 4已接单
        Integer status = param.get("status") != null ? StringUtil.getInt(param.get("status").toString(),-1) : -1;
        data = compUserService.queryApply(pageNum, rows, userId, compId, name, roleId, province, status);
        result = "00";
        message = "获取成功";
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 代理管理
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/queryAgent")
    public Map queryAgent(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        //登录名 姓名
        String name = param.get("name") != null ? param.get("name").toString() : "";
        //手机号
        String mobilePhone = param.get("mobilePhone") != null ? param.get("mobilePhone").toString() : "";

        //省
        String province = param.get("province") != null ? param.get("province").toString() : "";

        //产品名称
        String productName = param.get("productName") != null ? param.get("productName").toString() : "";
        //公司
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        //部门角色
        Integer roleId = param.get("roleId") != null ? StringUtil.getInt(param.get("roleId").toString(),0) : 0;
        Integer pageNum = param.get("pageNum") != null ? Integer.parseInt(param.get("pageNum").toString()) : 1;
        Integer rows = param.get("rows") != null ? Integer.parseInt(param.get("rows").toString()) : 10;
        //用户
        Integer userId = param.get("userId") != null ? StringUtil.getInt(param.get("userId").toString(),0) : 0;
        //1-正常代理 2产品下架,删除3-取消代理4-返点发生变化
        Integer status = param.get("status") != null ? StringUtil.getInt(param.get("status").toString(),-1) : -1;
        //代理时间
        String time = param.get("time") != null ? param.get("time").toString() : "";


        data = compUserService.queryAgent(pageNum, rows, userId, compId, name,mobilePhone ,roleId, province, productName,time,status);
        result = "00";
        message = "获取成功";
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }

    /**
     * 用户详情
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/getApplyDetail")
    public Map getApplyDetail(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        Integer applyId = param.get("applyId") != null ? Integer.parseInt(param.get("applyId").toString()) : 0;
        //公司
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        data = compUserService.getApplyDetail(applyId,compId);
        result = "00";
        message = "获取成功";
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 代理详情
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/getAgentDetail")
    public Map getAgentDetail(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        Integer productId = param.get("productId") != null ? Integer.parseInt(param.get("productId").toString()) : 0;
        //公司
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        data = compUserService.getAgentDetail(productId,compId);
        result = "00";
        message = "获取成功";
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }

    /**
     * 代理的申请信息
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/getAgentApply")
    public Map getAgentApply(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        Integer pageNum = param.get("pageNum") != null ? Integer.parseInt(param.get("pageNum").toString()) : 1;
        Integer rows = param.get("rows") != null ? Integer.parseInt(param.get("rows").toString()) : 10;
        //原产品
        Integer productId = param.get("productId") != null ? Integer.parseInt(param.get("productId").toString()) : 0;
        //公司
        Integer compId = param.get("compId") != null ? Integer.parseInt(param.get("compId").toString()) : 0;
        //代理人
        Integer userId = param.get("userId") != null ? Integer.parseInt(param.get("userId").toString()) : 0;

        data = compUserService.getAgentApply(pageNum,rows,productId,compId,userId);
        result = "00";
        message = "获取成功";
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 添加备注
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/addRemark")
    public Map addRemark(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
        //附件
        List<UploadFile> fList = (List<UploadFile>) request.getAttribute("fileField");

        Map<String, Object> urlMap = new HashMap<String, Object>();
        if (fList != null && fList.size() > 0) {
            urlMap = FileUploadUtil.uploadByInStream(fList, imgUrl, "remark");
        }
        StringBuilder urlsbulidr = new StringBuilder();
        if (images != null && !images.isEmpty()) {
            for (String key : images.keySet()) {
                urlsbulidr.append(imgUrl + urlMap.get(key).toString() + ",");
            }
        }
        //图片
        String urls = urlsbulidr.toString();
        //json内容
        String content = param.get("content") != null ? param.get("content").toString() : "";
        //对象id type 1传applyId type 2传 prouductId
        int objId = param.get("objId") != null ? StringUtil.getInt(param.get("objId").toString(),0) : 0;
        //类型 1 用户管理（申请） 2 代理
        Integer type = param.get("type") != null ? Integer.parseInt(param.get("type").toString()) : 0;
        if (StringUtils.isEmpty(content) || type == 0 || objId == 0 ) {
            message = "参数有误";
        } else {
            CompRemark remark = new CompRemark();
            remark.setContent(content);
            remark.setObjId(objId);
            remark.setType(type);
            remark.setUrl1(urlMap.get("url1") != null ? imgUrl + urlMap.get("url1").toString() : "");
            remark.setUrl2(urlMap.get("url2") != null ? imgUrl + urlMap.get("url2").toString() : "");
            remark.setUrl3(urlMap.get("url3") != null ? imgUrl + urlMap.get("url3").toString() : "");
            remark.setUrl4(urlMap.get("url4") != null ? imgUrl + urlMap.get("url4").toString() : "");
            remark.setUrl5(urlMap.get("url5") != null ? imgUrl + urlMap.get("url5").toString() : "");
            remark.setUrl6(urlMap.get("url6") != null ? imgUrl + urlMap.get("url6").toString() : "");
            remark.setUrl7(urlMap.get("url7") != null ? imgUrl + urlMap.get("url7").toString() : "");
            remark.setUrl8(urlMap.get("url8") != null ? imgUrl + urlMap.get("url8").toString() : "");
            remark.setUrl9(urlMap.get("url9") != null ? imgUrl + urlMap.get("url9").toString() : "");
            remark.setUrl9(urlMap.get("file") != null ? imgUrl + urlMap.get("file").toString() : "");
            remark.setCreateTime(DateUtil.getTimeStr(new Date()));
            int update = compRemarkService.add(remark);
            if(update > 0){
                result ="00";
                message ="编辑成功";
            }
        }
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
    /**
     * 修改备注
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/updateRemark")
    public Map updateRemark(HttpServletRequest request) throws ServiceException {
        String result = "01";
        String message = "";
        Object data = null;
        JSONObject subjo = new JSONObject();
        String reqData = request.getAttribute("_reqData") != null ? request.getAttribute("_reqData").toString() : "";
        Map<String, Object> param = JsonUtils.readValue(reqData.toString());
        Object imgUrl = request.getAttribute("imgUrl");
        Map<String, Object> images = (Map<String, Object>) request.getAttribute("images");
        Map<String, Object> urlMap = new HashMap<String, Object>();
        //附件
        List<UploadFile> fList = (List<UploadFile>) request.getAttribute("fileField");

        if (fList != null && fList.size() > 0) {
            urlMap = FileUploadUtil.uploadByInStream(fList, imgUrl, "remark");
        }

        StringBuilder urlsbulidr = new StringBuilder();
        if (images != null && !images.isEmpty()) {
            for (String key : images.keySet()) {
                urlsbulidr.append(imgUrl + urlMap.get(key).toString() + ",");
            }
        }
        //图片
        String urls = urlsbulidr.toString();
        //json内容
        String content = param.get("content") != null ? param.get("content").toString() : "";
        //主键
        int remarkId = param.get("remarkId") != null ? StringUtil.getInt(param.get("remarkId").toString(),0) : 0;
        //类型 1 用户管理（申请） 2 代理
        Integer type = param.get("type") != null ? Integer.parseInt(param.get("type").toString()) : 0;
        //删除附件地址,逗号分隔
        String deFiles = param.get("deFiles") != null ? param.get("deFiles").toString() : "";
        String url1 = param.get("url1") != null ? param.get("url1").toString() : "";
        String url2 = param.get("url2") != null ? param.get("url2").toString() : "";
        String url3 = param.get("url3") != null ? param.get("url3").toString() : "";
        String url4 = param.get("url4") != null ? param.get("url4").toString() : "";
        String url5 = param.get("url5") != null ? param.get("url5").toString() : "";
        String url6 = param.get("url6") != null ? param.get("url6").toString() : "";
        String url7 = param.get("url7") != null ? param.get("url7").toString() : "";
        String url8 = param.get("url8") != null ? param.get("url8").toString() : "";
        String url9 = param.get("url9") != null ? param.get("url9").toString() : "";
        if (StringUtils.isEmpty(content) || type == 0 || remarkId == 0 ) {
            message = "参数有误";
        } else {
            CompRemark remark = new CompRemark();
            remark.setContent(content);
            remark.setRemarId(remarkId);
            remark.setType(type);
            remark.setUpdateTime(DateUtil.getTimeStr(new Date()));
            remark.setUrl1(url1);
            remark.setUrl2(url2);
            remark.setUrl3(url3);
            remark.setUrl4(url4);
            remark.setUrl5(url5);
            remark.setUrl6(url6);
            remark.setUrl7(url7);
            remark.setUrl8(url8);
            remark.setUrl9(url9);
            try {
                if(urlMap.get("url1") != null){
                    remark.setUrl1(urlMap.get("url1") != null ? imgUrl + urlMap.get("url1").toString() : "");
                }
                if(urlMap.get("url2") != null ){
                    remark.setUrl2(urlMap.get("url2") != null ? imgUrl + urlMap.get("url2").toString() : "");

                }
                if(urlMap.get("url3") != null ){
                    remark.setUrl3(urlMap.get("url3") != null ? imgUrl + urlMap.get("url3").toString() : "");

                }
                if(urlMap.get("url4") != null){
                    remark.setUrl4(urlMap.get("url4") != null ? imgUrl + urlMap.get("url4").toString() : "");

                }
                if(urlMap.get("url5") != null){
                    remark.setUrl5(urlMap.get("url5") != null ? imgUrl + urlMap.get("url5").toString() : "");

                }
                if(urlMap.get("url6") != null ){
                    remark.setUrl6(urlMap.get("url6") != null ? imgUrl + urlMap.get("url6").toString() : "");

                }
                if(urlMap.get("url7") != null ){
                    remark.setUrl7(urlMap.get("url7") != null ? imgUrl + urlMap.get("url7").toString() : "");

                }
                if(urlMap.get("url8") != null ){
                    remark.setUrl8(urlMap.get("url8") != null ? imgUrl + urlMap.get("url8").toString() : "");

                }
                if(urlMap.get("url9") != null ){
                    remark.setUrl9(urlMap.get("url9") != null ? imgUrl + urlMap.get("url9").toString() : "");

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            int update = compRemarkService.update(remark);
            if(update > 0){
                if(!com.smartlbs.util.StringUtil.containEmpty(deFiles)){
                    try {
                        for (String s : deFiles.split(",")) {
                            FileUploadUtil.deleteFile(s);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                result ="00";
                message ="编辑成功";
            }
        }
        subjo.put("message", message);
        subjo.put("result", result);
        subjo.put("data", data);
        return subjo;
    }
}
